// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/functions/prestosql/map_top_n.h>

namespace kumo::pollux::functions {
    template<typename TExec>
    struct MapKeysByTopNValuesFunction {
        POLLUX_DEFINE_FUNCTION_TYPES(TExec);

        void call(
            out_type<Array<Orderable<T1> > > &out,
            const arg_type<Map<Orderable<T1>, Orderable<T2> > > &inputMap,
            int64_t n) {
            POLLUX_USER_CHECK_GE(n, 0, "n must be greater than or equal to 0");

            if (n == 0) {
                return;
            }

            using It = typename arg_type<Map<Orderable<T1>, Orderable<T2> > >::Iterator;
            // utilize comparator from MapTopNFunction to sort the input map.
            using Compare = typename MapTopNFunction<TExec>::template Compare<It>;
            const Compare comparator;

            std::priority_queue<It, std::vector<It>, Compare> topEntries;

            for (auto it = inputMap.begin(); it != inputMap.end(); ++it) {
                if (topEntries.size() < n) {
                    topEntries.push(it);
                } else if (comparator(it, topEntries.top())) {
                    topEntries.pop();
                    topEntries.push(it);
                }
            }

            std::vector<It> result;
            result.reserve(topEntries.size());
            while (!topEntries.empty()) {
                result.push_back(topEntries.top());
                topEntries.pop();
            }

            // Output the results in descending order.
            for (auto it = result.crbegin(); it != result.crend(); ++it) {
                out.push_back((*it)->first);
            }
        }
    };
} // namespace kumo::pollux::functions
